//
//  HomePageViewController.m
//  runingBabyModel
//
//  Created by lanou3g on 15/7/17.
//  Copyright (c) 2015年 lanou3g. All rights reserved.
//

#import "HomePageViewController.h"
#import "JSONKit.h"
#import "ViewController.h"
#import "lifeDetailViewController.h"
#import "UIView+MJExtension.h"
#import "MJRefresh.h"
#import "MJRefreshHeader.h"
#import "MainViewController.h"
@interface HomePageViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic,retain)NSMutableDictionary *mainViewDic;
@property (nonatomic,retain)UIView *BabyDetailView;
@property (nonatomic,retain)UILabel *babyTodayLabel;
@property (nonatomic,retain)UILabel *childBirthdayDistanceLabel_2;
@property (nonatomic,retain)UILabel *childHeightLabel_2;
@property (nonatomic,retain)UILabel *childweightLabel_2;
@property (nonatomic,retain)UILabel *momChangeLabel;
@property (nonatomic,retain)UILabel *momTitleLabel;
@property (nonatomic,retain)UITableView *adviseTabelView;
@property (nonatomic,retain)UIScrollView *homePageScrollView;
@property (nonatomic,assign)NSInteger dateToBirth;
//@property (nonatomic,retain)NSString *category;
//@property (nonatomic,retain)NSString *content;
//@property (nonatomic,retain)NSString *imageUrl;
@property (nonatomic,assign)NSInteger *dayToBirth;
@property (nonatomic,retain)NSDate *nowDate;
@property (nonatomic,retain)NSString *nowDateString;
@end

@implementation HomePageViewController



- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Do any additional setup after loading the view.
    
    
    [self homePageLayout];
    //[self chooseBirthDate];
    [self getData];
    
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:255 / 256.0 green:204 / 256.0 blue:204 / 256.0 alpha:1];
    self.navigationController.navigationBar.tintColor = [UIColor brownColor];
    
    UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:@"设置预产期" style:UIBarButtonItemStylePlain target:self action:@selector(chooseBirthDate:)];
    
    self.navigationItem.rightBarButtonItem = rightButton;
    [self refeshing];
}





//获取最新数据 刷新视图
-(void)getDateData{
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy年MM月dd日"];
    
    self.nowDate = [NSDate date];
    self.nowDateString = [dateFormatter stringFromDate:_nowDate];
    
    NSDate *dateFromBirth = [[NSUserDefaults standardUserDefaults] valueForKey:@"selectData"];
    if (dateFromBirth == nil) {
        [[NSUserDefaults standardUserDefaults] setObject:_nowDate forKey:@"selectData"];
    }
    
    //计算当前时间和预产期的天数差
    long dd = [dateFromBirth timeIntervalSince1970] - [_nowDate timeIntervalSince1970];
    self.dateToBirth = (dd + 86400)/ 86400 + 1;
    self.navigationItem.title = [NSString stringWithFormat:@"宝宝%ld天",280 - _dateToBirth];

}


-(void)viewWillAppear:(BOOL)animated{
    [self getData];
}




-(void)getData{
    [self getDateData];
    NSURL *url = [[NSURL alloc] initWithString:[NSString stringWithFormat:@"http://data.tataquan.com/api?gestation_info=%ld&mode=1&device_id=8A494966-7E98-4A74-A0DE-46AE925BA4A9&platform=ios&app_id=1&v=1.7.2&bundleid=1.7.2.6",280 - _dateToBirth]];
    
    //设置距离预产期的天数
    _childBirthdayDistanceLabel_2.text = [NSString stringWithFormat:@"%ld天",_dateToBirth];

    
    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
    [urlRequest setHTTPMethod:@"POST"];
    NSArray *postArr = @[@"suggestion", @"cookbook", @"remind",@"toptopic",@"article"];
    NSString *postStr = [postArr JSONString];
    NSData *postData = [postStr dataUsingEncoding:NSUTF8StringEncoding];
    [urlRequest setHTTPBody:postData];
    [NSURLConnection sendAsynchronousRequest:urlRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (data) {
            self.mainViewDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            //NSLog(@"%@",_mainViewDic);
            //求宝宝介绍的描述内容
            NSDictionary *babyDic = [_mainViewDic valueForKey:@"article"];
            NSString *babyToday = [babyDic valueForKey:@"article"];
            CGFloat height_baby = [HomePageViewController stringHeight:babyToday];
            //妈妈今日变化
            NSString *momToday = [babyDic valueForKey:@"mom_article"];
            CGFloat height_mom = [HomePageViewController stringHeight:momToday];
            //宝宝身长
            NSString *height = [NSString stringWithFormat:@"%@mm",[babyDic valueForKey:@"height"]];
            //宝宝体重
            NSString *weight = [NSString stringWithFormat:@"%@g",[babyDic valueForKey:@"weight"]];
            
            
            _BabyDetailView.frame = CGRectMake(0, 0, 375, 350 + height_baby);
            _babyTodayLabel.frame = CGRectMake(10, 335,355, height_baby);
            _babyTodayLabel.text = babyToday;
            _childHeightLabel_2.text = height;
            _childweightLabel_2.text = weight;
            
            _momTitleLabel.frame = CGRectMake(10, 355 + height_baby + 5, 355, 35);
            _momTitleLabel.text = @"妈妈变化";
            _momTitleLabel.font = [UIFont systemFontOfSize:20];
            _momTitleLabel.textColor =[UIColor colorWithRed:255 / 256.0 green:204 / 256.0 blue:204 / 256.0 alpha:1];
            
            _momChangeLabel.frame = CGRectMake(10, 355 + height_baby + 10 + 25, 355, height_mom);
            
            _momChangeLabel.text = momToday;
            
            [_adviseTabelView reloadData];
            
            
            
        }
    }];
    
}

-(void)homePageLayout{
    
    
    self.homePageScrollView = [[UIScrollView alloc] initWithFrame:self.view.frame];
    _homePageScrollView.contentSize = CGSizeMake(375, 850);
    [self.view addSubview:_homePageScrollView];
    self.BabyDetailView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 375, 350)];
    //BabyDetailView.backgroundColor = [UIColor grayColor];
    _BabyDetailView.backgroundColor = [UIColor colorWithRed:255 / 256.0 green:204 / 256.0 blue:204 / 256.0 alpha:1];
    [_homePageScrollView addSubview:_BabyDetailView];
    //布局当天日期
    UILabel *todayDateLabel = [[UILabel alloc] initWithFrame:CGRectMake(100, 10, 175, 35)];
    todayDateLabel.textAlignment = NSTextAlignmentCenter;
    todayDateLabel.text = _nowDateString;
    [_BabyDetailView addSubview:todayDateLabel];
    //布局imageView
    UIImageView *babyImageView = [[UIImageView alloc] initWithFrame:CGRectMake(100, 60, 175, 175)];
    babyImageView.image = [UIImage imageNamed:@"baby.jpg"];
    babyImageView.layer.cornerRadius = 175 / 2;
    babyImageView.contentMode = UIViewContentModeScaleAspectFill;
    babyImageView.layer.masksToBounds = YES;
    [_BabyDetailView addSubview:babyImageView];
    
    //布局imageView
    UIImageView *playImageView = [[UIImageView alloc] initWithFrame:CGRectMake(160, 120, 55 , 55)];
    playImageView.image = [UIImage imageNamed:@"play.png"];
    playImageView.layer.cornerRadius = 55 / 2;
    playImageView.contentMode = UIViewContentModeScaleAspectFill;
    playImageView.layer.masksToBounds = YES;
    [_BabyDetailView addSubview:playImageView];
    playImageView.userInteractionEnabled = YES;
    UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(playBabyMovie:)];
    [playImageView addGestureRecognizer:tapGR];
    
    
    //三个label:距离预产期  宝宝身长  宝宝体重
    UILabel *childBirthdayDistanceLabel_1 = [[UILabel alloc] initWithFrame:CGRectMake(25, 250, 75, 35)];
    childBirthdayDistanceLabel_1.text = @"距离预产期";
    childBirthdayDistanceLabel_1.font = [UIFont systemFontOfSize:15];
    childBirthdayDistanceLabel_1.textAlignment = NSTextAlignmentCenter;
    [_BabyDetailView addSubview:childBirthdayDistanceLabel_1];
    
    UILabel *childHeightLabel_1 = [[UILabel alloc] initWithFrame:CGRectMake(150, 250, 75, 35)];
    childHeightLabel_1.text = @"宝宝身长";
    childHeightLabel_1.font = [UIFont systemFontOfSize:15];
    childHeightLabel_1.textAlignment = NSTextAlignmentCenter;
    [_BabyDetailView addSubview:childHeightLabel_1];
    
    UILabel *childweightLabel_1 = [[UILabel alloc] initWithFrame:CGRectMake(275, 250, 75, 35)];
    childweightLabel_1.text = @"宝宝体重";
    childHeightLabel_1.font = [UIFont systemFontOfSize:15];
    childHeightLabel_1.textAlignment = NSTextAlignmentCenter;
    [_BabyDetailView addSubview:childweightLabel_1];
    
    //三个label:距离预产期  宝宝身长  宝宝体重
    self.childBirthdayDistanceLabel_2 = [[UILabel alloc] initWithFrame:CGRectMake(25, 290, 75, 35)];
    _childBirthdayDistanceLabel_2.text = @"0天";
    _childBirthdayDistanceLabel_2.font = [UIFont systemFontOfSize:25];
    _childBirthdayDistanceLabel_2.textAlignment = NSTextAlignmentCenter;
    [_BabyDetailView addSubview:_childBirthdayDistanceLabel_2];
    
    self.childHeightLabel_2 = [[UILabel alloc] initWithFrame:CGRectMake(150, 290, 85, 35)];
    _childHeightLabel_2.text = @"0mm";
    _childHeightLabel_2.font = [UIFont systemFontOfSize:25];
    _childHeightLabel_2.textAlignment = NSTextAlignmentCenter;
    [_BabyDetailView addSubview:_childHeightLabel_2];
    
    self.childweightLabel_2 = [[UILabel alloc] initWithFrame:CGRectMake(275, 290, 75, 35)];
    _childweightLabel_2.text = @"0g";
    _childweightLabel_2.font = [UIFont systemFontOfSize:25];
    _childweightLabel_2.textAlignment = NSTextAlignmentCenter;
    [_BabyDetailView addSubview:_childweightLabel_2];
    
    //宝宝现状
    self.babyTodayLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 335,355, 60)];
    _babyTodayLabel.numberOfLines = 0;
    _babyTodayLabel.text = @"请刷新数据...";
    [_BabyDetailView addSubview:_babyTodayLabel];
    
    //妈妈现状
    
    self.momTitleLabel = [[UILabel alloc] init];
    [_homePageScrollView addSubview:_momTitleLabel];
    
    self.momChangeLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 420, 355, 60)];
    _momChangeLabel.numberOfLines = 0;
    [_homePageScrollView addSubview:_momChangeLabel];
    
    self.adviseTabelView = [[UITableView alloc] initWithFrame:CGRectMake(0, 560, 375, 280) style:UITableViewStyleGrouped];
    _adviseTabelView.dataSource = self;
    _adviseTabelView.delegate = self;
    [_homePageScrollView addSubview:_adviseTabelView];

}

//显示预产期选取页面
-(void)chooseBirthDate:(UIBarButtonItem *)barButton{
    
        MainViewController *dateChooseVC = [[MainViewController alloc] init];
        [self presentViewController:dateChooseVC animated:YES completion:nil];
        //[self.view addSubview:dateChooseVC.view];
        //self.navigationController.tabBarController.tabBar.hidden = YES;
        //[self hideTabBar];

}





#pragma mark - 下拉刷新
-(void)refeshing{
    __weak __typeof(self) weakSelf = self;
    
    // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
    self.homePageScrollView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf loadNewData];
    }];
    
    // 马上进入刷新状态
    [_homePageScrollView.header beginRefreshing];
    
}

- (void)loadNewData
{
    // 1.添加数据
    [self getData];
    // 拿到当前的下拉刷新控件，结束刷新状态
    [_homePageScrollView.header endRefreshing];
    
}







//计算一个字符串的高度
+ (CGFloat)stringHeight:(NSString *)string{
    //设置字符串属性
    NSDictionary *dic = @{NSFontAttributeName : [UIFont systemFontOfSize:17]};
    
    //计算字符串区域
    CGRect rect = [string boundingRectWithSize:CGSizeMake(300, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    
    
    return rect.size.height;
}




-(void)playBabyMovie:(UITapGestureRecognizer *)tap{
    ViewController *babyMVC = [[ViewController alloc] init];
    [self hideTabBar];
    [self.navigationController pushViewController:babyMVC animated:YES];
}
#pragma mark - tableView必须实现的协议方法
//确定有多少个分组
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
//设置行高
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60;
}


//自定义分区标题视图
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    //只要返回一个试图指针就可以
    UILabel *label = [[UILabel alloc] init];
    label.text = @"生活指南";
    label.backgroundColor = [UIColor colorWithRed:255 / 256.0 green:204 / 256.0 blue:204 / 256.0 alpha:1];
    label.font = [UIFont systemFontOfSize:20];
    return label;
}




//标题栏行高
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 35;
}
//每个分组有多少个元素
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 4;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSArray *nameArr = @[@"examination",@"nutrition",@"lifeClass",@"study"];
    static NSString *momAdv = @"advCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:momAdv];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:momAdv];
    }
    //获取显示的数据
    NSArray *array = [_mainViewDic valueForKey: @"remind"];
    NSDictionary *dic = [array objectAtIndex:indexPath.row];
//    self.category = [dic valueForKey:@"category"];
//    self.content = [dic valueForKey:@"content"];
//    self.imageUrl = [dic valueForKey:@"image"];
    cell.textLabel.text = [dic valueForKey:@"category"];
    cell.detailTextLabel.text = [dic valueForKey:@"content"];
    cell.imageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@.png",[nameArr objectAtIndex:indexPath.row]]];
    return cell;
}

//选中某一行触发的方法
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSArray *array = [_mainViewDic valueForKey:@"remind"];
    NSDictionary *dic = [array objectAtIndex:indexPath.row];
    lifeDetailViewController *lifeDetailVC = [[lifeDetailViewController alloc] init];
    lifeDetailVC.categoryDetail = [dic valueForKey:@"category"];
    lifeDetailVC.contentDetail = [dic valueForKey:@"content"];
    lifeDetailVC.imageUrlDetail = [dic valueForKey:@"image"];
    lifeDetailVC.number = indexPath.row;
    [self.navigationController pushViewController:lifeDetailVC animated:YES];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


//隐藏tabBar
- (void)hideTabBar {
    if (self.tabBarController.tabBar.hidden == YES) {
        return;
    }
    UIView *contentView;
    if ( [[self.tabBarController.view.subviews objectAtIndex:0] isKindOfClass:[UITabBar class]] )
        contentView = [self.tabBarController.view.subviews objectAtIndex:1];
    else
        contentView = [self.tabBarController.view.subviews objectAtIndex:0];
    contentView.frame = CGRectMake(contentView.bounds.origin.x,  contentView.bounds.origin.y,  contentView.bounds.size.width, contentView.bounds.size.height + self.tabBarController.tabBar.frame.size.height);
    self.tabBarController.tabBar.hidden = YES;
    
}





/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
